<template>
  <el-form ref="form" :model="userForm" :rules="rules" label-width="7rem">
    <el-form-item label="用户昵称" prop="nickName">
      <el-input v-model="userForm.nickName" maxlength="30" />
    </el-form-item>
    <el-form-item label="手机号码" prop="tel">
      <el-input v-model="userForm.tel" maxlength="11" />
    </el-form-item>
    <el-form-item label="邮箱" prop="email">
      <el-input v-model="userForm.email" maxlength="50" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" size="small" @click="submit">保存</el-button>
      <el-button type="danger" size="small" @click="close">关闭</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup>
import { useTemplateRef } from 'vue'
import tab from '@/plugins/tab.js'

const props = defineProps({
  user: {
    type: Object,
    default: () => {}
  }
})
const userForm = ref({})
const emits = defineEmits(['save'])

watch(() => props.user, val => {
  userForm.value = {...val}
}, {immediate: true})

const formRef = useTemplateRef('form')
const rules = {
  email: [
    {
      type: 'email',
      message: "'请输入正确的邮箱地址",
      trigger: ['blur', 'change']
    }
  ],
  tel: [
    {
      pattern: /^1[3|456789][0-9]\d{8}$/,
      message: '请输入正确的手机号码',
      trigger: 'blur'
    }
  ]
}
const submit = () => {
  formRef.value.validate(valid => {
    if (valid) {
      $xl.apis.updateAdminUserBaseInfo({
        params: {
          nickName: userForm.value.nickName || '',
          tel: userForm.value.tel || '',
          email: userForm.value.email || ''
        }
      }).then(() => {
        emits('save', userForm.value)
        $xl.modal.msgSuccess('修改成功')
      })
    }
  })
}
const close = () => {
  userForm.value = {...props.user}
  tab.closePage()
}
</script>
